<?php

namespace app\home\controller;

use alipay\Pagepay;
use alipay\Notify;
use app\common\model\Category;
use app\common\model\Goods;
use app\common\model\Order;
use app\common\model\Subgoods;
use think\Controller;
use app\common\model\User;
use think\Session;
use think\Db;

/**
 *  订单管理
 * Class Flow
 * @package app\home\controller
 */

// 判断是否登陆，如果没有登陆，登陆后在操作
// 地址信息 如果有就用个人中心的
// 如果没有就添加

class Flow extends Controller
{
    private $categoryData;
    private $goods_id = array();//结算商品id数组

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        if(!Session::get('user.user_id')){
            $this->error('请先登陆后在进行结算','/login.html');
        }
        // 调取分类数据
        // 获取后台分类表数据
        $this->categoryData = (new Category())->where('pid',0)->select();
    }
    /**
     *  结算页面
     */
    public function index(){
        // 获取地址栏数据
        // 获取地址栏信息
        $model = User::get(Session::get('user.user_id'));

        $address = Db::name('userinfo')->where('default',1)->select();
        if($address){
            $address[0]['address'] = json_decode($address[0]['address'],true);
        }
        $goodsData = Session::get('cart');
        if (request()->isPost()){
            if(!input('post.address')){
                $this->error('没有收货地址');
            }
//            $model = new Order();
//            $model->order_name = 'ZY-'.Session::get('user.user_username').time();
//            $model->address_id = input('post.address');
//            $model->status = '未发货';
//            $model->price = $goodsData['total'];
//            $model->phone = input('post.phone');
//            $model->username = input('post.username');
//            $model->user_id = Session::get('user.user_id');
//            $model->note = input('post.note');
//
//            $model->goods_info = json_encode($goodsData,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
//            $res = $model->save();
//            if($res){
//                // 商品表中想要数据减少
//                foreach ($goodsData['goods'] as $k=>$v){
//                    $num = $v['options'][0]['snum']-$v['num'];
//                    Subgoods::where('id',$v['options'][0]['id'])->update(['snum'=>$num]);
//                }
//                // 清空购物车信息
//                Session::delete('cart');
//                $this->success('商品购买成功','/');
//            }else{
//                $this->error('购买失败');
//            }
        }
        // 将商品信息添加
        if(!is_null($goodsData)){
            foreach ($goodsData['goods'] as $k=>$v){
                $info = Goods::get($v['id'])->toArray();
                //记录结算商品id
                array_push( $this->goods_id,$v['id']);
                $goodsData['goods'][$k]['info'] = $info;
            }
        }
        $categoryData = $this->categoryData;
//        var_dump($this->goods_id);
        return view('',compact('categoryData','address','goodsData'));
    }
    public function toPay()
    {
        $params['subject'] = 'JS_chen商城测试';
        $params['out_trade_no'] = $this->getTradeNo();
        $params['total_amount'] = request()->post('total');
        $goodsData = Session::get('cart');
        $goods_id = '';
        foreach ($goodsData['goods'] as $k=>$v) {
            if($goods_id == '')
            {
                $goods_id = $v['id'];
            }else{
                $goods_id = $goods_id .','.$v['id'];
            }
        }
        $data = [
            'out_trade_no'=> $params['out_trade_no'],
            'trade_no'=>'',
            'pay_price'=>$params['total_amount'],
            'goods_id'=>$goods_id,
            'user_id'=>Session::get('user.user_id'),
            'address'=>request()->post('address'),
            'phone'=>request()->post('phone'),
            'message'=>request()->post('note'),
            'nickname'=>request()->post('username')
        ];
        Db::name('order')->insert($data);
        // 清空购物车信息
        Session::delete('cart');
        //去支付
        Pagepay::pay($params);
    }
    public function returnUrl()
    {
        $out_trade_no = request()->get('out_trade_no');
        $trade_no = request()->get('trade_no');
        $order = Db::name('order')->where('out_trade_no',$out_trade_no)->find();
        if($order)
        {
            $params['out_trade_no'] = $order['out_trade_no'];
            $params['total_amount'] = $order['pay_price'];
            if(Notify::check($params,'get'))
            {
                //更新订单状态 1未支付，2未发货，3已发货，4已签收
                $data = ['order_status'=>2,'trade_no'=>$trade_no];
                Db::name('order')->where('out_trade_no',$out_trade_no)->update($data);
                return $this->redirect('/orderlist.html');
            }else{
                echo "签名检验错误";exit;
            }
        }else{
            echo "订单不存在";exit;
        }
    }
    public function notiyf()
    {
        $out_trade_no = request()->post('out_trade_no');
        $trade_no = request()->post('trade_no');
        $trade_status = request()->post('trade_status');
        $whereData = ['out_trade_no'=>$out_trade_no,'trade_no'=>''];
        $order = Db::name('order')->where($whereData)->find();
        if($order)
        {
            $params['out_trade_no'] = $order['out_trade_no'];
            $params['total_amount'] = $order['pay_price'];
            if(Notify::check($params,"post"))
            {
                if($trade_status == "TRADE_SUCCESS")
                {
                    //更新订单状态
                    $data = ['order_status'=>1,'trade_no'=>$trade_no];
                    Db::name('order')->where('out_trade_no',$out_trade_no)->update($data);
                    return $this->redirect('/orderlist.html');
                }
            }else{
                echo "签名检验错误";exit;
            }
        }else{
            echo "订单不存在";exit;
        }
    }
    /**
     * Notes:生成订单号
     * User: 'JS_chen'
     * Date: 2018/6/23
     * Time: 11:48
     * @return string
     */
    public function getTradeNo()
    {
        $out_trade_no = date("YmdHis",time()).Session::get('user.user_id').random_int(01,100);
        return $out_trade_no;
    }
}
